import axios from 'axios'
import router from '../router/index.js'
import { Loading, Message } from 'element-ui'
import storageHelper from './storageHelper'

let loading //定义loading变量
let needLoadingRequestCount = 0

function startLoading() {
	if (needLoadingRequestCount === 0) {
		loading = Loading.service({
			lock: true,
			text: '正在努力加载中...',
			background: 'rgba(0, 0, 0, 0.7)',
		})
	}
	needLoadingRequestCount++
}

function endLoading() {
	if (needLoadingRequestCount > 0) {
		needLoadingRequestCount--
	}
	if (needLoadingRequestCount === 0) {
		loading.close()
	}
}

//默认值
if (process.env.NODE_ENV === 'development') {
	// axios.defaults.baseURL = '';
	axios.defaults.baseURL = 'https://api.mabangerp.com'
} else {
	axios.defaults.baseURL = 'https://api.mabangerp.com'
	// axios.defaults.baseURL = '/api';
}
axios.defaults.headers.post['Content-Type'] = 'application/json' //application/x-www-form-urlencoded
axios.defaults.timeout = 60000
//请求拦截器
axios.interceptors.request.use(
	(config) => {
		if (config.data instanceof FormData) {
			config.headers = {
				'Content-Type': 'multipart/form-data',
			}
		} else {
			config.data = JSON.stringify(config.data)
			config.headers = {
				'Content-Type': 'application/json',
			}
		}

		config.headers.Authorization = 'Bearer ' + storageHelper.get('mabangerp_token')
		config.headers.ProjectId = 'ddb'
		startLoading()
		// config.withCredentials = true;
		return config
	},
	(error) => {
		Message.error({ message: '请求超时!' })
		return Promise.reject(error)
	}
)
//响应拦截器
axios.interceptors.response.use(
	(res) => {
		endLoading()
		let resData = res.data
		if (resData.code === 200) {
			return resData.data
		} else {
			Message.error({ message: resData.msg })
			router.push('/')
			return
		}
	},
	(error) => {
		if (!error.response) {
			Message.error({ message: '您的网络断掉了!' })
		}
		if (error.response.status == 504 || error.response.status == 404) {
			Message.error({ message: '安全验证过期，请重新登陆!' })
		} else if (error.response.status == 403) {
			Message.error({ message: '安全验证过期，请重新登陆!' })
			router.push('/')
		} else {
			Message.error({ message: '发生错误!!' })
		}
		endLoading()
		return Promise.reject(error)
	}
)
export default axios
